package bsc.war.ajax;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author castrosalazar
 */

public class PopableWindow extends AbstractController
{

    public PopableWindow()
    {

    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            request.setAttribute("url", request.getParameter("url"));
            String tmpParams = request.getParameter("params");

            /* ** UPDATE! **
             * The parameters were processed into a JSON to use the $.get ajax call to load
             * the requested url and parameters and insert html in a div. It wasn't compatible
             * with iOS Safari and probably many other browsers. Instead, for more compatibility,
             * an iframe loads the requested url and parameters in a URL encoded line.
             * JSON-construction related code is commented; as well as in the JSP.
             */

            /* Jquery (in the JSP view) makes a $.get ajax call with the specified URL
             * and the needed parameters in a JSON String. The link that calls this controller
             * must specify the parameters with the colons sign and separated with semi-colons.
             * Ex: popableWindow.do?url=dashboardProject.do&params=scoreCard:1;title:shalala;author:rcs
             */

            StringTokenizer token = new StringTokenizer(tmpParams, ":;");
            StringBuffer /*paramsJSON = new StringBuffer(),*/ paramsLink = new StringBuffer();
            //paramsJSON.append("{");
            while(token.hasMoreTokens())
            {
                String tmp = token.nextToken();
                //paramsJSON.append(" '");
                //paramsJSON.append(tmp);
                paramsLink.append(tmp);
                //paramsJSON.append("': '");
                paramsLink.append("=");
                tmp = token.nextToken();
                //paramsJSON.append(tmp);
                paramsLink.append(tmp);
                //paramsJSON.append("'");
                if(token.hasMoreTokens())
                {
                    //paramsJSON.append(",");
                    paramsLink.append("&");
                }
            }
            //paramsJSON.append("}");
            //request.setAttribute("params", paramsJSON.toString());
            request.setAttribute("paramsLink",paramsLink.toString());
            response.setContentType("text/html");
        } catch (Exception e) {
            logger.error("Caught exception: ", e);
        }
        return new ModelAndView("popableWindow");
    }
}
